package com.leo.basic.scheduler.service.impl;

import com.leo.basic.scheduler.bean.OperLog;
import com.leo.basic.scheduler.dao.OperLogMapper;
import com.leo.basic.scheduler.service.IOperLogService;
import com.leo.config.DataSourceConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @ClassName OperLogServiceImpl
 * @Description 任务操作日志记录
 * @Author wangss
 * @date 2021.09.23 14:51
 * @Version 1.0
 */
@Slf4j
@Service("operLogServcie")
public class OperLogServiceImpl implements IOperLogService {

    /**
     * 日志记录缓存队列
     */
    private ConcurrentLinkedQueue<OperLog> queue = new ConcurrentLinkedQueue<>();

    @Resource
    private OperLogMapper mapper;

    @Async
    @Override
    public void asyncLog(OperLog operLog) {
        queue.add(operLog);
        if (queue.size() > 100) {
            log.info("日志队列大小超过[{}],进行操作日志保存", 100);
            persistOperLog();
        }
    }

    @Async
    @Scheduled(fixedRate = 30000)
    @Override
    public void persistOperLog() {
        while (queue.size() > 0) {
            mapper.insert(DataSourceConfig.systemOperLogTableName, queue.poll());
        }
    }

    @Override
    public List<OperLog> getOperLogListByJobName(String jobName) {
        return mapper.getOperLogListByJobName(DataSourceConfig.systemOperLogTableName, jobName);
    }
}
